import { useState, useCallback } from 'react';
import { FileHandle, SyncStatus, NovelStructure } from '../../types/fileSystem.ts';
import { useFileSystem } from './useFileSystem.ts';
import { ItemType, TreeItem } from '../../types/novel.ts';
import { autoImportNovelStructure, AutoImportResult, FolderPattern } from '../../utils/fileSystem/autoImporter.ts';
import { registerFileHandle } from '../../utils/file/fileSystem.ts';
import { preserveTextFormat } from '../../utils/fileSystem/textFormatUtils.ts';

export interface FileSyncState {
    status: SyncStatus;
    error: string | null;
    lastSynced: Date | null;
    rootFolder: FileHandle | null;
    syncEnabled: boolean;
    novelStructure: NovelStructure | null;
    autoImportResult: AutoImportResult | null;
}

/**
 * 文件同步Hook
 * 管理文件系统同步状态和操作
 */
export function useFileSync() {
    const fileSystem = useFileSystem();

    // 同步状态
    const [syncState, setSyncState] = useState<FileSyncState>({
        status: 'idle',
        error: null,
        lastSynced: null,
        rootFolder: null,
        syncEnabled: false,
        novelStructure: null,
        autoImportResult: null
    });

    // 更新部分状态
    const updateSyncState = useCallback((updates: Partial<FileSyncState>) => {
        setSyncState(prev => ({ ...prev, ...updates }));
    }, []);

    // 扫描文件夹结构
    const scanFolder = useCallback(async (folder: FileHandle) => {
        if (!folder) return null;

        try {
            updateSyncState({ status: 'syncing', error: null });

            // 检查文件夹权限
            const hasPermission = await fileSystem.checkPermission(folder);
            if (!hasPermission) {
                const granted = await fileSystem.requestPermission(folder);
                if (!granted) {
                    throw new Error('没有文件夹访问权限');
                }
            }

            // 使用文件系统服务扫描小说结构
            const structure = await fileSystem.scanNovelStructure(folder);

            updateSyncState({
                status: 'idle',
                novelStructure: structure,
                lastSynced: new Date()
            });

            return structure;
        } catch (error) {
            console.error('扫描文件夹失败:', error);
            updateSyncState({
                status: 'error',
                error: error instanceof Error ? error.message : '扫描文件夹失败'
            });
            return null;
        }
    }, [fileSystem, updateSyncState]);

    // 将文件结构转换为小说树结构
    const convertToNovelStructure = useCallback(async (structure: NovelStructure): Promise<TreeItem | null> => {
        if (!structure || !structure.rootFolder) return null;

        // 创建小说
        const novel: TreeItem = {
            id: structure.rootFolder.id,
            name: structure.rootFolder.name,
            type: ItemType.NOVEL,
            fileHandle: structure.rootFolder,
            children: []
        };

        // 注册文件句柄
        registerFileHandle(structure.rootFolder.id, structure.rootFolder);

        // 添加卷和章节
        for (const volume of structure.volumes) {
            const volumeItem: TreeItem = {
                id: volume.folder.id,
                name: volume.folder.name,
                type: ItemType.VOLUME,
                fileHandle: volume.folder,
                children: []
            };

            // 注册文件句柄
            registerFileHandle(volume.folder.id, volume.folder);

            // 添加章节
            for (const chapter of volume.chapters) {
                // 注册文件句柄
                registerFileHandle(chapter.file.id, chapter.file);

                // 读取章节内容
                let chapterContent = '';
                try {
                    // 如果已经有内容（预加载），则使用它
                    if (chapter.content) {
                        chapterContent = chapter.content;
                    } else {
                        // 否则从文件读取内容
                        console.log(`从文件读取章节内容: ${chapter.file.name}`);
                        const rawContent = await fileSystem.readTextFile(chapter.file);
                        chapterContent = preserveTextFormat(rawContent);
                    }
                } catch (error) {
                    console.error(`读取章节内容失败: ${chapter.file.name}`, error);
                    // 失败时使用空内容，但不阻止导入流程
                    chapterContent = '';
                }

                volumeItem.children?.push({
                    id: chapter.file.id,
                    name: chapter.file.name,
                    type: ItemType.CHAPTER,
                    fileHandle: chapter.file,
                    content: chapterContent
                });
            }

            novel.children?.push(volumeItem);
        }

        return novel;
    }, [fileSystem]);

    // 开始同步
    const startSync = useCallback(async () => {
        if (!syncState.rootFolder || syncState.status === 'syncing') return null;

        try {
            updateSyncState({ status: 'syncing', error: null });

            // 检查文件夹权限
            const hasPermission = await fileSystem.checkPermission(syncState.rootFolder);
            if (!hasPermission) {
                const granted = await fileSystem.requestPermission(syncState.rootFolder);
                if (!granted) {
                    throw new Error('没有文件夹访问权限');
                }
            }

            // 重新扫描文件结构
            const structure = await fileSystem.scanNovelStructure(syncState.rootFolder);

            // 更新同步完成状态
            updateSyncState({
                status: 'idle',
                novelStructure: structure,
                lastSynced: new Date()
            });

            // 转换为小说结构
            const novelStructure = await convertToNovelStructure(structure);
            return novelStructure;
        } catch (error) {
            console.error('文件同步失败:', error);
            updateSyncState({
                status: 'error',
                error: error instanceof Error ? error.message : '未知错误'
            });
            return null;
        }
    }, [fileSystem, syncState.rootFolder, syncState.status, updateSyncState, convertToNovelStructure]);

    // 选择根文件夹并扫描
    const selectRootFolder = useCallback(async () => {
        try {
            const folder = await fileSystem.selectFolder();
            if (folder) {
                updateSyncState({
                    rootFolder: folder,
                    status: 'idle',
                    error: null
                });

                // 自动扫描选择的文件夹
                const structure = await scanFolder(folder);
                return {
                    folder,
                    structure
                };
            }
        } catch (error) {
            console.error('选择文件夹失败:', error);
            updateSyncState({
                status: 'error',
                error: error instanceof Error ? error.message : '选择文件夹失败'
            });
        }
        return null;
    }, [fileSystem, scanFolder, updateSyncState]);

    // 自动导入小说结构
    const autoImportFromFolder = useCallback(async (folder?: FileHandle) => {
        try {
            // 使用提供的文件夹或当前设置的根文件夹
            const targetFolder = folder || syncState.rootFolder;
            if (!targetFolder) {
                throw new Error('未选择文件夹');
            }

            updateSyncState({ status: 'syncing', error: null });

            // 1. 扫描文件夹结构
            const structure = await scanFolder(targetFolder);
            if (!structure) {
                throw new Error('扫描文件夹失败');
            }

            // 2. 自动识别并导入
            const result = await autoImportNovelStructure(structure);

            // 3. 更新状态
            updateSyncState({
                status: result.success ? 'idle' : 'error',
                error: result.success ? null : result.error,
                autoImportResult: result,
                lastSynced: new Date()
            });

            console.log('自动导入结果:', result.success ? '成功' : '失败',
                result.novel?.name || '',
                '模式:', result.pattern);

            return result;
        } catch (error) {
            console.error('自动导入失败:', error);
            const errorMessage = error instanceof Error ? error.message : '自动导入失败';
            updateSyncState({
                status: 'error',
                error: errorMessage,
                autoImportResult: {
                    novel: null,
                    pattern: FolderPattern.UNKNOWN,
                    success: false,
                    error: errorMessage
                }
            });
            return null;
        }
    }, [syncState.rootFolder, scanFolder, updateSyncState]);

    // 导入小说结构
    const importNovelStructure = useCallback(async (structure: NovelStructure | null): Promise<TreeItem | null> => {
        if (!structure) return null;

        try {
            updateSyncState({ status: 'syncing', error: null });

            // 转换文件结构为小说结构
            const novelStructure = await convertToNovelStructure(structure);

            if (novelStructure) {
                updateSyncState({
                    status: 'idle',
                    lastSynced: new Date()
                });
            }

            return novelStructure;
        } catch (error) {
            console.error('导入小说结构失败:', error);
            updateSyncState({
                status: 'error',
                error: error instanceof Error ? error.message : '导入小说结构失败'
            });
            return null;
        }
    }, [convertToNovelStructure, updateSyncState]);

    // 开关同步功能
    const toggleSync = useCallback((enabled?: boolean) => {
        const newState = enabled !== undefined ? enabled : !syncState.syncEnabled;
        updateSyncState({ syncEnabled: newState });
    }, [syncState.syncEnabled, updateSyncState]);

    // 清除同步状态
    const clearSync = useCallback(() => {
        setSyncState({
            status: 'idle',
            error: null,
            lastSynced: null,
            rootFolder: null,
            syncEnabled: false,
            novelStructure: null,
            autoImportResult: null
        });
    }, []);

    return {
        // 状态
        syncState,

        // 操作
        startSync,
        selectRootFolder,
        scanFolder,
        toggleSync,
        clearSync,
        importNovelStructure,
        convertToNovelStructure,
        autoImportFromFolder,

        // 工具方法
        isSyncing: syncState.status === 'syncing',
        hasError: syncState.status === 'error',
        hasSyncFolder: !!syncState.rootFolder
    };
} 